package app.poi;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import app.util.URLConnectionDownloader;
import app.util.UUIDUtil;

public class ExcelPicDownload extends ABasePoiService {
	
	private String targetFileDirPath;
	
	@Override
	public String setSourceFilePath() {
		return "C:/download/二手房备份.xls";
	}
	
	@Override
	public String setTargetFileDirPath() {
		return "C:/download/";
	}
	
	public void dealWorkbook() throws FileNotFoundException, IOException {
		HSSFWorkbook workbook = getWorkbook();
		int numberOfSheets = workbook.getNumberOfSheets();
		for (int i = 0; i < numberOfSheets; i++) {
			HSSFSheet sheetAt = workbook.getSheetAt(i);
			String sheetName = sheetAt.getSheetName();
			targetFileDirPath = setTargetFileDirPath() + File.separator + sheetName + File.separator;
			createTargetFileDir(targetFileDirPath);
			dealRows(sheetAt);
		}
		File outFile = new File(setSourceFilePath());
		OutputStream os = new FileOutputStream(outFile);
		workbook.write(os);
	}
	
	public void dealRows(HSSFSheet sheetAt){
		int physicalNumberOfRows = sheetAt.getPhysicalNumberOfRows();
		for (int i = 1; i < physicalNumberOfRows; i++) {
			HSSFRow row = sheetAt.getRow(i);
			dealOneRowCells(row);
		}
		dealOneRowCells(sheetAt.createRow(physicalNumberOfRows+1));
	}
	
	public void dealOneRowCells(HSSFRow row) {
		int physicalNumberOfCells = row.getPhysicalNumberOfCells();
		row.createCell(physicalNumberOfCells+1);
		HSSFCell cell = row.getCell(0);
		String tel = row.getCell(2).getStringCellValue();
		try {
			String uuid = UUIDUtil.getUUID();
			URLConnectionDownloader.download(cell.getStringCellValue(),targetFileDirPath,uuid+".jpg");
			row.getCell(physicalNumberOfCells+1).setCellValue(uuid);
		} catch (Exception e) {
			row.getCell(physicalNumberOfCells+1).setCellValue("下载失败");
			e.printStackTrace();
		}
	}
}
